package com.cjdx.supermarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjdx.supermarket.entity.User;
import com.cjdx.supermarket.mapper.UserMapper;
import com.cjdx.supermarket.service.UserService;
import com.cjdx.supermarket.util.PasswordUtil;
import com.cjdx.supermarket.util.R;
import com.cjdx.supermarket.util.StatusCode;
import org.springframework.stereotype.Service;

/**
 * @Author: wanjianhong
 * @Version: 1.0
 * @Description: 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 用户登录
     * @param userCode 用户名
     * @param password 密码
     * @return 登录结果
     */
    @Override
    public R login(String userCode, String password) {
        // 参数校验
        if (userCode == null || userCode.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            return R.createError(StatusCode.ERROR, "用户名或密码不能为空");
        }

        // 根据用户名查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userCode", userCode);
        User user = getOne(queryWrapper);

        // 用户不存在
        if (user == null) {
            return R.createError(StatusCode.ERROR, "用户名或密码错误");
        }

        // 验证密码
        boolean isMatch = PasswordUtil.match(password, user.getUserPassword());
        if (!isMatch) {
            return R.createError(StatusCode.ERROR, "用户名或密码错误");
        }

        // 登录成功，清除敏感信息
        user.setUserPassword(null);
        user.setSalt(null);

        return R.createSuccess(user);
    }
}
